package com.jwb.config.security;

import com.jwb.util.Md5Str;
import com.jwb.util.RSA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityEncoder implements PasswordEncoder {

    @Autowired
    private RSAKey rsaKey;
    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {
        return Md5Str.str2MD5to16byte(rawPassword.toString());
//        return bCryptPasswordEncoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword){
        try {
            String password = RSA.decrypt(rawPassword.toString(), rsaKey.getPrivate_key());
//          前端RSA加密，后端RSA解密后 与数据库加密密码匹配
//          return bCryptPasswordEncoder.matches(password,encodedPassword);
            return encodedPassword.equals(Md5Str.str2MD5to16byte(password));
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        return false;
    }
}
